import { reqCartList,reqDeleteCartById,reqUpdateCheckCart } from "@/api"
const state={
    cartList:[]
}
const mutations={
    GETCARTLIST(state,cartList){
        state.cartList=cartList
    }
}
const actions={
    //获取购物车列表数据
    async getCartList({commit}){
      let result=  await reqCartList();
      //console.log(result);
      if(result.code==200){
          commit('GETCARTLIST',result.data)
      }  
    },
    async deleteCartListBySkuId({commit},skuId){
        let result=await reqDeleteCartById(skuId)
        if(result==200){
            return "ok"
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    async updateCheckedById({commit},{skuId,isChecked}){
        let result=await reqUpdateCheckCart(skuId,isChecked);
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //修改全部商品的状态
    updateAllCartIsChecked({dispatch,state},isChecked){
        console.log(state,isChecked);
        let promiseAll=[]
        state.cartList[0].cartInfoList.forEach(item=>{
            let promise=dispatch('updateCheckedById',{skuId:item.skuId,isChecked})//最终会返回一个promise
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    },
    deleteAllCheckedCart({dispatch,getters}){
       //context上下文
       //获取购物车中全部产品
       let PromiseAll=[]
       getters.cartList[0].cartInfoList.forEach(item => {
           let promise=item.isChecked==1?dispatch('deleteCartListBySkuId',item.skuId):''
           PromiseAll.push(promise)
       });
       return Promise.all(PromiseAll)
    }
}
const getters={
    cartList(state){
        return state.cartList[0]||{}
    }
}
export default{
    state,
    mutations,
    actions,
    getters
}